package com.itheima.blog.auth.interceptor;

import com.itheima.blog.util.UserThreadLocalUtils;
import com.itheima.blog.util.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String adminUserId = request.getHeader(Constants.HEADER_USER_ID_ADMIN);
        if(StringUtils.hasLength(adminUserId)){
            // 存入ThreadLocal
            UserThreadLocalUtils.setAdminUserId(Integer.valueOf(adminUserId));
        }
        String webUserId = request.getHeader(Constants.HEADER_USER_ID_WEB);
        if(StringUtils.hasLength(webUserId)){
            // 存入ThreadLocal
            UserThreadLocalUtils.setWebUserId(Integer.valueOf(webUserId));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocalUtils.removeUser();
    }
}
